#include "./video_widget.h"
#include "../utils/error.h"
#include <QResizeEvent>
#include "../../app.h"


VideoWidget::VideoWidget(QWidget *parent) : QLabel(parent) {
}

VideoWidget::~VideoWidget() {
    m_play_flag = false;
    try {

        if (m_playex != nullptr) {
            m_playex->exit();
        }
        if (m_play_task.joinable()) {
            m_play_task.join();
        }

    } catch (const std::exception &e) {
        debug("play stop exception");
        debug(e.what());
    }

}

void VideoWidget::resizeEvent(QResizeEvent *event) {
    QWidget::resizeEvent(event);
}

void VideoWidget::refresh(ImageWrap &&image) {

    run_on_ui([this, img = std::move(image)]() {
        setPixmap( QPixmap::fromImage( std::move(img.image) ) );
    });
}

void VideoWidget::play(const QString &file_path) {

    try {
        if (m_playex != nullptr) {
            m_playex->exit();
            m_playex->wait_finish();
            m_playex = nullptr;
        }
    } catch (const std::exception &e) {
        debug("play stop exception");
        debug(e.what());
    }

    m_playex = std::make_unique<PlayEx>(
        file_path, 
        width(), height(), 
        std::bind(&VideoWidget::refresh, this, std::placeholders::_1) 
    );
    m_playex->play();

}

void VideoWidget::play_files(const QStringList &file_paths) {
    if (file_paths.isEmpty()) {
        return;
    }
    m_files = file_paths;
    m_file_index = 0;
    m_play_flag = true;
    play_next();
}

void VideoWidget::play_next() {
    if (!m_play_flag) {
        return;
    }
    if (m_file_index >= m_files.size()) {
        m_file_index = 0;
    }

    try {

        if (m_playex != nullptr) {
            m_playex->exit();
        }
        if (m_play_task.joinable()) {
            m_play_task.join();
        }

    } catch (const std::exception &e) {
        debug("play stop exception");
        debug(e.what());
    }

    QString file_path = m_files[m_file_index];
    m_file_index += 1;

    m_playex = std::make_unique<PlayEx>(
        file_path, 
        width(), height(), 
        std::bind(&VideoWidget::refresh, this, std::placeholders::_1) 
    );
    m_playex->play();

    m_play_task = std::thread([this](){

        try {
            m_playex->wait_finish();
            run_on_ui( [this]() { play_next(); } );
        } catch (const std::exception &e) {
            debug("play wait stop exception");
            debug(e.what());
        }
    });
}

